﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.Logging;
using Furion.Logging.Extensions;
using FaceMqttClient.model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceMqttClient.services
{
    public class RfidService : ITransient
    {
        private readonly ISqlSugarClient db;

        public RfidService(ISqlSugarClient db)
        {
            this.db = db;
        }
        public List<rfid_down_log> Getallrfid(String devid, int size = 100, int page = 0)
        {
            
            var dev_ = db.Queryable<Weixin_dev, Weixin_org>((st, sc) => new object[] {
                        JoinType.Inner,st.orgid==sc.id}).Where((st, sc) => st.Id == devid).Select((st, sc) => new { school = sc.school_id }).First();

            if (dev_ == null)
            {
                return null;
            }


            var school = dev_.school;

            var aschool = db.Queryable<School>().Where(sc => sc.id == school).First();

            if (aschool == null)
            {
                return null;

            }
            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);

            var afd = db.Queryable<rfid_down_log>().Where(fd => fd.SN == devid).Max(fd => fd.time);

            if (afd > datetime)
            {
                datetime = afd;
            }



            var sql = $"  INSERT INTO lxb_rfid_down_log(user_id,username,rfid,time,status,islock,SN) " +
                $" select user_id,username,rfid, uptime as time,  0 as status,islock, '{devid}' as SN from lxb_user" +
                $" where  (rfid > 0 or rfid= -1 )and slname='{aschool.name}'  and  uptime > '{datetime.ToString("yyyy/MM/dd HH:mm:ss")}'";

            //Console.WriteLine(sql);
            StringLoggingPart.Default().SetMessage(sql).LogWarning();

            db.Ado.ExecuteCommand(sql);

            var avu = db.Queryable<rfid_down_log>().Where((fd) => fd.status == 0 && fd.times < 5 && fd.SN == devid)
              .OrderBy(fd => fd.id, OrderByType.Asc).Take(size).ToList();
            foreach (var item in avu)
            {
                var it = db.Queryable<wall>().Where(w => w.user_id == item.user_id).First();
                item.blance = (it == null) ? 0 : (it.PV - it.LPV) + it.TPV;

            }

            return avu;
        }

        public void resetdown(String devid)
        {
            db.Deleteable<rfid_down_log>().Where(r => r.SN == devid).ExecuteCommand();
        }

        public List<wall_down_log> GetWallrfid(String devid, int size = 100, int page = 0)
        {
            var dev_ = db.Queryable<Weixin_dev, Weixin_org>((st, sc) => new object[] {
                        JoinType.Inner,st.orgid==sc.id}).Where((st, sc) => st.Id == devid).Select((st, sc) => new { school = sc.school_id }).First();

            if (dev_ == null)
            {
                return null;
            }


            var school = dev_.school;

            var aschool = db.Queryable<School>().Where(sc => sc.id == school).First();

            if (aschool == null)
            {
                return null;

            }
            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);

            var afd = db.Queryable<wall_down_log>().Where(fd => fd.SN == devid).Max(fd => fd.time);

            if (afd > datetime)
            {
                datetime = afd;
            }



            var sql = $"  INSERT INTO lxb_wall_down_log(user_id,username,PV,TPV,time,status,SN) " +
                $" select  lxb_user.user_id,username,(lxb_wall.PV - lxb_wall.LPV) as PV,TPV , lxb_wall.last as time,  0 as status, '{devid}' as SN from lxb_user" +
                $" INNER JOIN lxb_wall ON lxb_wall.user_id =lxb_user.user_id where  rfid<>'' and slname='{aschool.name}'  and   lxb_wall.last > '{datetime.ToString("yyyy/MM/dd HH:mm:ss")}'";

            // Console.WriteLine(sql);

            db.Ado.ExecuteCommand(sql);

            Console.ForegroundColor = ConsoleColor.Green;
            var avu = db.Queryable<wall_down_log>().Where((fd) => fd.status == 0 && fd.times < 5 && fd.SN == devid)
              .OrderBy(fd => fd.id, OrderByType.Asc).Take(size).ToList();

            Console.ForegroundColor = ConsoleColor.White;
            return avu;
        }

        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="SN"> 设备SN</param>
        /// <param name="id">id</param>
        /// <param name="status">状态</param>
        /// <param name="why">原因</param>
        /// <returns></returns>
        public Boolean Uprfidstate(String SN, String ids, int status = 1, string why = "")
        {
            var sql = "";
            if (status == 1)
            {
                sql = $"update  lxb_rfid_down_log  set status =1 where SN='{SN}' and  id in ({ids})";
            }
            else
            {
                sql = $"update  lxb_rfid_down_log  set status =0 ,times=times+1  where SN='{SN}' and  id in ( {ids})";
            }

        //    sql.LogWarning();

            db.Ado.ExecuteCommandAsync(sql);
            return true;
        }
        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="SN"> 设备SN</param>
        /// <param name="id">id</param>
        /// <param name="status">状态</param>
        /// <param name="why">原因</param>
        /// <returns></returns>
        public Boolean UpBalancestate(String SN, String ids, int status = 1, string why = "")
        {
            var sql = "";
            if (status == 1)
            {
                sql = $"update  lxb_wall_down_log  set status =1 where SN='{SN}' and  id in ({ids})";
            }
            else
            {
                sql = $"update  lxb_wall_down_log  set status =0 ,times=times+1  where SN='{SN}' and  id in( {ids})";
            }
           // sql.LogWarning();

            db.Ado.ExecuteCommandAsync(sql);
            return true;
        }

        private string path = AppDomain.CurrentDomain.BaseDirectory;
        private String dellasttime = "";
        public List<Users_del> GetDel(String devid, int size = 100, int page = 0)
        {
            var dev_ = db.Queryable<Weixin_dev, Weixin_org>((st, sc) => new object[] {
                        JoinType.Inner,st.orgid==sc.id}).Where((st, sc) => st.Id == devid).Select((st, sc) => new { school = sc.school_id }).First();

            if (dev_ == null)
            {
                return null;
            }





            var schoolid = dev_.school;
            var sch = db.Queryable<School>().First(s => s.id == schoolid);

            if (sch == null)
            {
                return null;
            }
            var school = sch.name;

            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);
            try
            {
                datestr = System.IO.File.ReadAllText($"{path}dev/{devid}_d.cfg");
                datetime = Convert.ToDateTime(datestr);
            }
            catch (Exception)
            {
                datestr = "2018/1/1";
            }

            var lst = db.Queryable<Users_del>().Where(d => d.deltime > datetime && d.School == school).OrderBy(d => d.deltime, OrderByType.Asc).Skip(page * size).Take(size).ToList();
            if (lst.Count > 0)
            {
                dellasttime = lst.Last().deltime.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (lst.Count < size && (!String.IsNullOrEmpty(dellasttime)))
            {
                try
                {
                    if (!Directory.Exists($"{path}dev/"))
                    {
                        Directory.CreateDirectory($"{path}dev/");
                    }
                    System.IO.File.WriteAllText($"{path}dev/{devid}_d.cfg", dellasttime);

                }
                catch (Exception ex)
                {
                    Console.WriteLine( ex.Message );
                    ex.Message.LogWarning();
                }

            }
            return lst;
        }

    }
}
